-
Notifications
You must be signed in to change notification settings - Fork 92
gpfup-count-files-groups.js: Added snippet to count files in groups.
#1116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gpfup-count-files-groups.js: Added snippet to count files in groups.
#1116
Conversation
|
""" WalkthroughA new JavaScript module is added to dynamically count files uploaded through grouped file upload fields in a Gravity Forms form using the Gravity Perks File Upload Pro plugin. The script updates designated number fields with the total count of files uploaded in their associated groups, responding in real time to file upload changes. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Form (DOM)
participant GPFUP Plugin
participant Script
User->>Form (DOM): Uploads/removes file(s)
Form (DOM)->>GPFUP Plugin: Handles file upload
GPFUP Plugin-->>Script: Emits file set event (Vuex mutation)
Script->>Script: Recalculate total files for each group
Script->>Form (DOM): Update number field(s) with new count
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (1)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (6)
gp-file-upload-pro/gpfup-count-files-groups.js (6)
7-7: Consider using modern JavaScript declarations.The code works correctly with the global
GFFORMIDvariable. Consider usingconstinstead ofvarfor better code quality and to prevent accidental reassignment.-var formId = GFFORMID; +const formId = GFFORMID;
9-14: Clear configuration structure.The mapping configuration is well-structured and documented. Consider using
constfor immutable configuration data.-var countMapping = { +const countMapping = {
25-34: Efficient reverse lookup construction.The logic correctly builds the reverse mapping using functional programming patterns. Consider using
constand modern destructuring syntax.-var uploadToCountMap = {}; -Object.entries(countMapping).forEach(function ([countFieldID, uploadFieldIDs]) { +const uploadToCountMap = {}; +Object.entries(countMapping).forEach(([countFieldID, uploadFieldIDs]) => { - uploadFieldIDs.forEach(function (uploadFieldID) { + uploadFieldIDs.forEach((uploadFieldID) => {
36-48: Improve robustness with optional chaining and error handling.The core logic is correct. Consider using optional chaining as suggested by static analysis and add error handling for missing DOM elements.
function updateAllCountFields() { - Object.entries(countMapping).forEach(function ([countFieldID, uploadFieldIDs]) { - var total = uploadFieldIDs.reduce(function (sum, uploadFieldID) { - var key = 'GPFUP_' + formId + '_' + uploadFieldID; - var store = window[key] && window[key].$store; + Object.entries(countMapping).forEach(([countFieldID, uploadFieldIDs]) => { + const total = uploadFieldIDs.reduce((sum, uploadFieldID) => { + const key = 'GPFUP_' + formId + '_' + uploadFieldID; + const store = window[key]?.$store; return sum + (store ? (store.state.files.length || 0) : 0); }, 0); - var selector = '#input_' + formId + '_' + countFieldID; - jQuery(selector).val(total).change(); + const selector = '#input_' + formId + '_' + countFieldID; + const $field = jQuery(selector); + if ($field.length) { + $field.val(total).change(); + } }); }🧰 Tools
🪛 Biome (1.9.4)
[error] 41-41: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
50-63: Efficient event subscription with proper filtering.The subscription logic correctly identifies relevant fields and listens for the appropriate mutation type. Consider modernizing the syntax for consistency.
-gpfupInstances.forEach(function (key) { - var parts = key.split('_'); - var fieldID = parseInt(parts[2]); // GPFUP_formId_fieldId - var store = window[key].$store; +gpfupInstances.forEach((key) => { + const parts = key.split('_'); + const fieldID = parseInt(parts[2]); // GPFUP_formId_fieldId + const store = window[key].$store; if (uploadToCountMap[fieldID]) { - store.subscribe(function (mutation, state) { + store.subscribe((mutation, state) => { if (mutation.type === 'SET_FILES') { updateAllCountFields(); } }); } });
1-67: Overall assessment: Good functionality with critical syntax fix needed.The script implements a useful feature for counting files across grouped upload fields. However, there's a critical syntax error that prevents execution. Consider these improvements:
- Critical: Fix the illegal return statement (line 22)
- Recommended: Use modern JavaScript syntax (
const/let, arrow functions, optional chaining)- Enhancement: Add comprehensive error handling for missing DOM elements and store instances
- Documentation: Consider adding JSDoc comments for the main function
Would you like me to provide a complete refactored version that addresses all these points and follows modern JavaScript best practices?
🧰 Tools
🪛 Biome (1.9.4)
[error] 22-22: Illegal return statement outside of a function
(parse)
[error] 41-41: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
gp-file-upload-pro/gpfup-count-files-groups.js(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js
[error] 22-22: Illegal return statement outside of a function
(parse)
[error] 41-41: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (2)
gp-file-upload-pro/gpfup-count-files-groups.js (2)
1-6: LGTM!Clear documentation header with helpful links to both general documentation and specific instruction video.
65-66: LGTM!Proper initialization to ensure counts are accurate on page load.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
gp-file-upload-pro/gpfup-count-files-groups.js (2)
9-14: Enhance configuration documentation for better usability.Consider adding more detailed documentation to help users understand how to configure the mapping correctly.
Add more comprehensive documentation:
// Map count field IDs to arrays of file upload field IDs +// Each key is a Number Field ID that will display the count +// Each value is an array of File Upload Field IDs to count files from +// Example: Field 5 will show total files from upload fields 1, 3, and 4 var countMapping = { - // Add more mappings if needed + // Add more mappings as needed: countFieldID: [uploadFieldID1, uploadFieldID2, ...] };
32-44: Core update logic is solid, consider modern syntax improvement.The function correctly calculates file counts and updates the DOM. The logic handles edge cases well.
Consider using optional chaining for cleaner code (addresses static analysis hint):
- var store = window[key] && window[key].$store; + var store = window[key]?.$store;This makes the code more readable while maintaining the same safety guarantees.
🧰 Tools
🪛 Biome (1.9.4)
[error] 37-37: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
gp-file-upload-pro/gpfup-count-files-groups.js(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js
[error] 37-37: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (5)
gp-file-upload-pro/gpfup-count-files-groups.js (5)
1-8: Well-documented file header with clear context.The documentation header provides excellent context with links to documentation and instruction video. The formId declaration follows standard Gravity Forms patterns.
16-19: Efficient GPFUP instance discovery implementation.The logic correctly identifies all GPFUP instances for the form using a clean pattern matching approach.
21-30: Well-implemented reverse lookup mapping.The reverse lookup logic correctly handles the many-to-many relationship between upload fields and count fields. The implementation properly accounts for multiple count fields that might depend on the same upload field.
46-61: Efficient event subscription with proper filtering.The subscription logic is well-optimized, only listening to relevant upload fields and the appropriate mutation type. The conditional check prevents unnecessary processing when no GPFUP instances exist.
63-64: Proper initialization ensures accurate counts on page load.The initial function call correctly sets up the count fields when the page loads.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (3)
gp-file-upload-pro/gpfup-count-files-groups.js (3)
17-17: Use consistent variable declarations.The code uses
varhere butconstelsewhere. For consistency and better scoping, useconstsince this variable is not reassigned.-var gpfupInstances = Object.keys(window).filter(function (key) { +const gpfupInstances = Object.keys(window).filter(function (key) {
37-37: Use optional chaining for cleaner code.The static analysis tool correctly identified that this can be simplified using optional chaining.
- const store = window[key] && window[key].$store; + const store = window[key]?.$store;🧰 Tools
🪛 Biome (1.9.4)
[error] 37-37: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
49-67: Good implementation with minor improvement suggestion.The subscription logic is well-implemented and efficiently uses the reverse lookup to only subscribe to relevant fields. The initial count call ensures proper state on page load.
Consider adding error handling for store subscription:
if (uploadToCountMap[fieldID]) { - store.subscribe((mutation, state) => { - if (mutation.type === 'SET_FILES') { - updateAllCountFields(); - } - }); + try { + store.subscribe((mutation, state) => { + if (mutation.type === 'SET_FILES') { + updateAllCountFields(); + } + }); + } catch (error) { + console.error('Failed to subscribe to store:', error); + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
gp-file-upload-pro/gpfup-count-files-groups.js(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js
[error] 37-37: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (1)
gp-file-upload-pro/gpfup-count-files-groups.js (1)
9-14: LGTM! Well-structured configuration mapping.The configuration object is clearly documented and provides a flexible way to define field relationships. The inline comments make it easy to understand the mapping structure.
`gpfup-count-files-groups.js`: Added snippet to count files in groups. `gpfup-count-files-groups.js`: Added snippet to count files in groups.
69a8201 to
68c80f2
Compare
veryspry
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@saifsultanc one suggestion / question!
| if (uploadToCountMap[fieldID]) { | ||
| store.subscribe((mutation, state) => { | ||
| if (mutation.type === 'SET_FILES') { | ||
| updateAllCountFields(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since uploadToCountMap[fieldID] has an array of all count fields that need updating, what do you think about passing that as a param to updateAllCountFields() to avoid recalculating anything unnecessary count fields?
It would also need to account for the initial "update" for all count fields then too if making this suggested addition
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done!
Context
⛑️ Ticket(s): https://secure.helpscout.net/conversation/2951970232/84219
Summary
Add support for grouping file upload fields in the GPFUP Count Files snippet. Allow defining multiple groups and assigning each group’s count to a different number field.
https://www.loom.com/share/2328e327125844bebdcabf7c9baaabca